<template>
    <el-card>
        <template #header>
            <h3>开具处方</h3>
        </template>
        <!-- 搜索区域 -->
        <el-form inline>
            <el-form-item label="药品名称" style="width: 200px">
                <el-input v-model="params.name"></el-input>
            </el-form-item>
            <el-form-item label="适应症" style="width: 150px">
                <el-input v-model="params.indications"></el-input>
            </el-form-item>
            <el-form-item label="生产商" style="width: 200px">
                <el-input v-model="params.manufacturer"></el-input>
            </el-form-item>
            <el-form-item label="批准文号" style="width: 200px">
                <el-input v-model="params.approvalNumber"></el-input>
            </el-form-item>
            <el-form-item label="OTC">
                <el-select v-model="params.isOTC" placeholder="" style="width: 60px">
                    <el-option v-for="item in OTCOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchmedication()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="medication" border>
            <!-- 扩展行 -->
            <el-table-column type="expand">
                <template #default="props">
                    <el-descriptions class="margin-top" :column="1" border>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">适应症：</div>
                            </template>
                            {{ props.row.indications }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">规格：</div>
                            </template>
                            {{ props.row.specification }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">用法用量：</div>
                            </template>
                            {{ props.row.dosage }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">单位：</div>
                            </template>
                            {{ props.row.unit }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">注意事项：</div>
                            </template>
                            {{ props.row.precautions }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">不良反应：</div>
                            </template>
                            {{ props.row.adverse_effects }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">有效期：</div>
                            </template>
                            {{ props.row.expiration_date }}
                        </el-descriptions-item>
                    </el-descriptions>
                </template>
            </el-table-column>
            <el-table-column label="图片" width="175" align="center">
                <template #default="scope">
                    <el-image v-if="scope.row.medication_img" :src="scope.row.medication_img"
                        class="medication-img"></el-image>
                    <el-image v-else src="src\assets\imgs\暂无图片.png" class="medication-img" />
                    <span v-if="scope.row.stock <= 10 && scope.row.stock > 0" class="stock">库存仅剩：{{ scope.row.stock
                        }}</span>
                    <span v-else-if="scope.row.stock == 0" class="stock">暂无库存</span>
                </template>
            </el-table-column>
            <el-table-column label="药品名称" prop="name" align="center"></el-table-column>
            <el-table-column label="价格" prop="price" align="center">
                <template #default="scope">
                    <div class="prices-count">
                        <span>￥{{ scope.row.price.toFixed(2) }}</span>
                        <el-input-number v-if="scope.row.count > 0" class="count" v-model="scope.row.count" :min="0"
                            @change="handleChange" size="default" />
                        <el-button v-else type="primary" @click="handleChange1(scope)">＋</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="生产商" prop="manufacturer" align="center"></el-table-column>
            <el-table-column label="批准文号" prop="approval_number" align="center"></el-table-column>
            <el-table-column label="OTC" align="center">
                <template #default="scope">
                    <span v-if="(scope.row.is_otc == false)">非</span>OTC
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 处方药品 -->
    <el-card class="cart-detail" v-if="showCart">
        <template #header>
            <div class="cart-title">
                <h3>处方药品</h3>
                <div class="clear" @click="clearCart()">
                    <img src="@\assets\imgs\清空购物车.png" alt="" class="clear-img">
                    <span class="clear-text">清空处方</span>
                </div>
            </div>
        </template>
        <el-table :data="cart" class="cart-table">
            <el-table-column label="" width="125">
                <template #default="scope">
                    <el-image :src="scope.row.medication_img" class="cart-medication-img" align="center"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="" prop="name" align="center"></el-table-column>
            <el-table-column label="" prop="price" width="90" align="center">
                <template #default="scope">
                    <div class="prices">
                        <span>￥{{ scope.row.price.toFixed(2) }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="" prop="count" width="120" align="center">
                <template #default="scope">
                    <div class="count-unit">
                        <el-input-number class="count-small" v-model="scope.row.count" :min="0"
                            @change="cardHandleChange" size="small">
                        </el-input-number>
                        <span>&nbsp;{{ scope.row.unit }}</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="cart-footer">
                <span class="total-price">
                    合计：
                    <span class="total-price-text">
                        ￥{{ totalPrice.toFixed(2) }}
                    </span>
                </span>
                <el-button type="primary" @click="pay">生成 / 修改处方</el-button>
            </div>
        </template>
    </el-card>
    <div class="cart-box">
        <img src="@/assets/imgs/药箱.png" alt="" class="cart" @click="showCart = !showCart">
        <div class="cart-count" v-if="(totalCount > 0)">{{ this.totalCount }}</div>
    </div>
</template>
<script>
import { medicationFindAPI } from '@/api/medication';
import { prescriptionAddOrUpdateAPI, prescriptionFindByHistoryIdAPI } from '@/api/prescription';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
    data() {
        return {
            params: {
                history_id: this.$route.params.id,
                // 搜索关键词
                name: '',
                indications: '',
                isOTC: '',
                manufacturer: '',
                approvalNumber: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            medication: [],
            cart: [],
            OTCOptions: [
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '0',
                    label: '否'
                },
                {
                    value: '1',
                    label: '是'
                }
            ],
            showCart: false,
            totalCount: 0,
            totalPrice: 0.00,
            prescription: {
                residentId: '',
                historyId: this.$route.params.id,
                institutionId: JSON.parse(sessionStorage.getItem('user')).institution_id,
                departmentId: JSON.parse(sessionStorage.getItem('user')).department_id,
                doctorId: JSON.parse(sessionStorage.getItem('user')).user_id,
                medications: '',
            }
        }
    },
    methods: {
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadMedicationList();
        },
        searchmedication() {
            this.handleCurrentChange(1);
        },
        loadMedicationList() {
            medicationFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.medication = resp.data.datas;
                    this.params.total = resp.data.total;
                    // 遍历medication
                    for (let i = 0; i < this.medication.length; i++) {
                        // 如果该行cart.count > 0，则使count = cart.count
                        if (this.cart.some(item => item.id === this.medication[i].id)) {
                            this.medication[i].count = this.cart.find(item => item.id === this.medication[i].id).count;
                        } else {
                            this.medication[i].count = 0;
                        }
                    }
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        handleChange() {
            this.totalCount = this.cart.reduce((pre, cur) => {
                if ((cur.count > cur.stock) && !cur.addMore) {
                    ElMessageBox.confirm(cur.name + ' 库存不足，确定继续添加吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        cur.addMore = true;
                    }).catch(() => {
                        cur.count = cur.stock;
                    });
                }
                return pre + cur.count;
            }, 0);
            this.totalPrice = this.cart.reduce((pre, cur) => {
                return pre + cur.price * cur.count;
            }, 0);
            // 更新 this.cart 数组
            this.cart = this.cart.map(item => {
                let medicationItem = this.medication.find(med => med.id === item.id);
                if (medicationItem) {
                    item.count = medicationItem.count;
                }
                return item;
            });
            if (Array.isArray(this.cart)) {
                this.cart = this.cart.concat(this.filteredMedication);
                // 相同id的只保留最后一次
                this.cart = this.cart.reduce((acc, cur) => {
                    const existingItem = acc.find(item => item.id === cur.id);
                    if (!existingItem) {
                        return acc.concat(cur);
                    }
                    return acc;
                }, []);
            } else {
                console.error('this.cart 不是数组:', this.cart);
            }

            // 如果cart.count = 0，从cart删除
            this.cart = this.cart.filter(item => item.count > 0);
            sessionStorage.setItem('cart', JSON.stringify(this.cart));
        },
        handleChange1(scope) {
            if (scope.row.count == 0) {
                scope.row.count += 2;
                this.handleChange();
                scope.row.count--;
                this.handleChange();
            }
        },
        cardHandleChange() {
            this.totalCount = this.cart.reduce((pre, cur) => {
                if ((cur.count > cur.stock) && !cur.addMore) {
                    ElMessageBox.confirm(cur.name + ' 库存不足，确定继续添加吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then((action) => {
                        cur.addMore = true;
                    }).catch(() => {
                        cur.count = cur.stock;
                        return;
                    });
                }
                return pre + cur.count;
            }, 0);
            this.totalPrice = this.cart.reduce((pre, cur) => {
                return pre + cur.price * cur.count;
            }, 0);
            // 更新 this.medication 数组
            this.medication = this.medication.map(item => {
                let cartItem = this.cart.find(med => med.id === item.id);
                if (cartItem) {
                    item.count = cartItem.count;
                }
                return item;
            });
            if (Array.isArray(this.cart)) {
                this.cart = this.cart.concat(this.filteredMedication);
                // 相同id的只保留最后一次
                this.cart = this.cart.reduce((acc, cur) => {
                    const existingItem = acc.find(item => item.id === cur.id);
                    if (!existingItem) {
                        return acc.concat(cur);
                    }
                    return acc;
                }, []);
            } else {
                console.error('this.cart 不是数组:', this.cart);
            }
            // 如果cart.count = 0，从cart删除
            this.cart = this.cart.filter(item => item.count > 0);
            sessionStorage.setItem('cart', JSON.stringify(this.cart));
        },
        pay() {
            // medications赋值为药品ID*药品数量,...,
            this.prescription.medications = this.cart.map(item => {
                if (item.count > 0) {
                    return item.id + "*" + item.count;
                }
            }).filter(item => item != undefined).join(",");
            // 去掉开头和结尾的所有逗号
            if (this.prescription.medications.startsWith(",")) {
                this.prescription.medications = this.prescription.medications.slice(1);
            }
            if (this.prescription.medications.endsWith(",")) {
                this.prescription.medications = this.prescription.medications.slice(0, -1);
            }

            if (this.prescription.medications == "" || this.prescription.medications == undefined || this.prescription.medications == null || this.prescription.medications.length == 0) {
                ElMessage.warning("请选择药品");
                return;
            }
            // 自动获取当前日期赋值给visit_date
            this.prescription.make_date = new Date().toLocaleDateString();
            prescriptionAddOrUpdateAPI(this.prescription).then((resp) => {
                if (resp.data.code == 2000) {
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        clearCart() {
            this.cart = [];
            this.totalCount = 0;
            this.totalPrice = 0;
            sessionStorage.setItem('cart', '[]');
            this.medication.forEach(item => {
                item.count = 0;
            });
        }
    },
    computed: {
        // 为购物车过滤出count > 0的药品数据
        filteredMedication() {
            return this.medication.filter(item => item.count > 0);
        },
        filteredCart() {
            return this.cart.filter(item => item.count > 0);
        }

    },
    created() {
        this.loadMedicationList();
        sessionStorage.setItem('cart', '[]');
        prescriptionFindByHistoryIdAPI(this.prescription).then(resp => {
            if (resp.data.code == 2000) {
                this.cart = resp.data.datas;
                sessionStorage.setItem('cart', JSON.stringify(this.cart));
                this.totalCount = this.cart.reduce((pre, cur) => {
                    return pre + cur.count;
                }, 0);
                this.totalPrice = this.cart.reduce((pre, cur) => {
                    return pre + cur.price * cur.count;
                }, 0);
                // ElMessage.success(resp.data.message);
            } else {
                // ElMessage.error(resp.data.message);
            }
        });
    }
}
</script>

<style scoped>
.example-pagination-block {
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-pagination {
    margin-top: 20px;
    justify-content: center;
    align-items: center;
}

.description {
    margin: 0px 15px;
}

.medication-img {
    width: 100%;
    height: 100%;
}

.stock {
    position: absolute;
    right: 15px;
    color: red;
    font-size: 16px;
    font-weight: bold;
    z-index: 999;
}

.prices-count {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.count {
    width: 100px;
}

.cart-box {
    position: fixed;
    right: 30px;
    top: 140px;
    z-index: 999;
}

.cart-box .cart {
    width: 70px;
    cursor: pointer;
}

.cart-detail {
    position: fixed;
    right: 100px;
    top: 90px;
    z-index: 999;
    width: 500px;
}

.cart-detail .cart-table {
    max-height: 370px;
    /* 显示滚动条 */
    overflow: auto;
}

.cart-detail .cart-medication-img {
    width: 100px;
    height: 100px;
}

.cart-detail .count-unit {
    display: flex;
}

.cart-detail .count-unit .count-small {
    width: 75px;
}

.cart-detail .cart-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.cart-detail .cart-title .clear {
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #999;
    transition: all .2s;

    &:hover {
        color: #666;
    }
}

.cart-detail .cart-title .clear .clear-img {
    width: 20px;
}

.cart-detail .cart-title .clear .clear-text {
    font-size: 14px;
}

.cart-count {
    position: absolute;
    right: 0;
    top: 0;
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%;
    color: #fff;
    text-align: center;
    font-weight: bold;
    line-height: 20px;
}

.cart-footer {
    line-height: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.total-price {
    margin-right: 10px;
}

.total-price .total-price-text {
    line-height: 20px;
    font-size: 20px;
    color: red;
}
</style>